package org.swift.commons.deployer.axis2.web;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.TransportListener;
import org.apache.axis2.transport.http.AxisServlet;

@SuppressWarnings("serial")
public class RjlgAxisServlet extends AxisServlet {

	private AxisConfiguration axisConfiguration = null;

	@Override
	protected ConfigurationContext initConfigContext(ServletConfig config)
			throws ServletException {
		try {
			ConfigurationContext configContext = super
					.initConfigContext(config);
			configContext.setProperty(Constants.CONTAINER_MANAGED,
					Constants.VALUE_TRUE);
			this.axisConfiguration = configContext.getAxisConfiguration();
			return configContext;
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	@SuppressWarnings("unchecked")
	protected void initializeHostName(HttpServletRequest request,
			AxisConfiguration configuration) throws AxisFault {
		if (configuration != null) {
			String serverName = request.getServerName();
			for (TransportInDescription inDescription : (Collection<TransportInDescription>) configuration
					.getTransportsIn().values()) {
				inDescription.addParameter(new Parameter(
						TransportListener.HOST_ADDRESS, serverName));
			}
			configuration.addParameter(TransportListener.HOST_ADDRESS,
					serverName);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		initializeHostName(req, this.axisConfiguration);
		super.doGet(req, resp);
	}
}